<template>
  <div class="category-view">
    <NavBar />
    <main class="container">
      <div class="category-header">
        <h1>{{ categoryName }}</h1>
        <p class="book-count">共 {{ allBooks.length }} 本书籍</p>
      </div>
      
      <LoadingSpinner v-if="isLoading" message="正在加载分类书籍..." />
      
      <div v-else>
        <div class="filters" v-if="allBooks.length > 0">
          <div class="filter-group">
            <label>价格区间:</label>
            <select v-model="priceFilter">
              <option value="all">全部价格</option>
              <option value="0-20">20元以下</option>
              <option value="20-50">20-50元</option>
              <option value="50-100">50-100元</option>
              <option value="100+">100元以上</option>
            </select>
          </div>
          
          <div class="filter-group">
            <label>品相:</label>
            <select v-model="conditionFilter">
              <option value="all">全部品相</option>
              <option value="new">几乎全新</option>
              <option value="good">品相良好</option>
              <option value="used">有使用痕迹</option>
            </select>
          </div>
          
          <div class="filter-group">
            <label>排序方式:</label>
            <select v-model="sortBy">
              <option value="default">默认排序</option>
              <option value="price-asc">价格从低到高</option>
              <option value="price-desc">价格从高到低</option>
              <option value="condition">品相优先</option>
            </select>
          </div>
        </div>
        
        <div class="book-list" v-if="filteredBooks.length > 0">
          <div class="books-grid">
            <div class="book-card" v-for="book in filteredBooks" :key="book.id" @click="viewBookDetails(book.id)">
              <div class="book-cover">
                <img :src="getCoverUrl(book)" :alt="book.title">
              </div>
              <div class="book-info">
                <h4>{{ book.title }}</h4>
                <p class="book-author">{{ book.author }}</p>
                <p class="book-price">¥{{ book.price }}</p>
                <p class="book-seller">卖家: {{ book.seller_name }}</p>
                <div class="book-tags">
                  <span v-if="book.book_condition === 'new'" class="tag tag-new">几乎全新</span>
                  <span v-else-if="book.book_condition === 'good'" class="tag tag-good">品相良好</span>
                  <span v-else-if="book.book_condition === 'used'" class="tag tag-used">有使用痕迹</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="no-results" v-else>
          <p>该分类下暂无书籍</p>
          <router-link to="/" class="back-link">返回首页</router-link>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import NavBar from '../components/NavBar.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import api from '@/api/apiClient'
import defaultCover from '@/assets/OIP.jpg' // 引入默认封面图片

const route = useRoute()
const router = useRouter()
const categoryId = computed(() => Number(route.query.id || 0))
const categoryName = computed(() => route.query.name || '全部分类')
const books = ref([])
const allBooks = ref([]) // 存储所有书籍数据
const priceFilter = ref('all')
const conditionFilter = ref('all')
const sortBy = ref('default')
const isLoading = ref(true)

onMounted(() => {
  fetchCategoryBooks()
})

// 监听categoryId变化，重新获取数据
watch(categoryId, () => {
  if (categoryId.value) {
    fetchCategoryBooks()
  }
})

const fetchCategoryBooks = async () => {
  isLoading.value = true
  try {
    if (!categoryId.value) {
      console.log('分类ID不存在，将显示空结果')
      allBooks.value = []
      isLoading.value = false
      return
    }
    
    console.log('获取分类书籍，分类ID:', categoryId.value)
    
    // 获取所有书籍
    const response = await api.book.getList({})
    
    // 输出响应进行调试
    console.log('原始响应:', response)
    
    // 检查响应格式并提取数据
    let data = []
    if (Array.isArray(response)) {
      // 如果是数组，直接使用
      data = response
      console.log('获取书籍数据成功 (数组格式)')
    } else if (response && response.code == 200 && response.data) {
      // 如果是包含code和data的对象，则使用response.data
      data = response.data
      console.log('获取书籍数据成功 (对象格式)')
    } else if (response && Array.isArray(response.books)) {
      // 另一种可能的响应格式
      data = response.books
      console.log('获取书籍数据成功 (books数组格式)')
    } else {
      console.error('获取分类书籍失败: 返回格式不正确', response)
      data = []
    }
    
    console.log('获取到的书籍总数:', data.length)
    
    // 根据分类ID筛选书籍，确保类型一致
    allBooks.value = data.filter(book => {
      const bookCategoryId = Number(book.category_id);
      const currentCategoryId = Number(categoryId.value);
      return bookCategoryId === currentCategoryId;
    });
    
    console.log('分类筛选后结果数量:', allBooks.value.length)
  } catch (error) {
    console.error('获取分类书籍失败:', error)
    allBooks.value = []
  } finally {
    isLoading.value = false
  }
}

// 价格区间过滤
const getPriceRange = (book, range) => {
  const price = parseFloat(book.price);
  switch(range) {
    case '0-20': return price <= 20;
    case '20-50': return price > 20 && price <= 50;
    case '50-100': return price > 50 && price <= 100;
    case '100+': return price > 100;
    default: return true; // 全部价格
  }
}

// 品相过滤
const getCondition = (book, condition) => {
  switch(condition) {
    case 'new': return book.book_condition === 'new';
    case 'good': return book.book_condition === 'good';
    case 'used': return book.book_condition === 'used';
    default: return true; // 全部品相
  }
}

// 监听筛选和排序条件变化
watch([priceFilter, conditionFilter, sortBy], () => {
  console.log('分类页筛选条件变化:', {
    价格: priceFilter.value,
    品相: conditionFilter.value,
    排序: sortBy.value
  });
})

// 前端筛选和排序
const filteredBooks = computed(() => {
  if (allBooks.value.length === 0) return [];
  
  console.log('执行分类页筛选，原始数据数量:', allBooks.value.length);
  
  // 先筛选
  let result = allBooks.value.filter(book => {
    const priceMatches = getPriceRange(book, priceFilter.value);
    const conditionMatches = getCondition(book, conditionFilter.value);
    return priceMatches && conditionMatches;
  });
  
  // 再排序
  if (sortBy.value === 'price-asc') {
    result.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
  } else if (sortBy.value === 'price-desc') {
    result.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
  } else if (sortBy.value === 'condition') {
    // 品相优先级：new > good > used
    const conditionValue = (condition) => {
      switch(condition) {
        case 'new': return 3;
        case 'good': return 2;
        case 'used': return 1;
        default: return 0;
      }
    };
    
    result.sort((a, b) => conditionValue(b.book_condition) - conditionValue(a.book_condition));
  }
  
  console.log('分类页筛选后数据数量:', result.length);
  return result;
})

const viewBookDetails = (bookId) => {
  router.push(`/book/${bookId}`)
}

// 添加获取封面URL的方法，与HomeView.vue保持一致
const getCoverUrl = (book) => {
  if (!book || !book.cover) {
    console.log('无封面数据，使用默认封面');
    return defaultCover;
  }
  
  try {
    // 检查是否为相对路径，添加基础URL
    if (typeof book.cover === 'string') {
      if (!book.cover.startsWith('http')) {
        // 对路径进行URL编码，确保特殊字符不会导致问题
        const encodedPath = book.cover.split('/').map(segment => encodeURIComponent(segment)).join('/');
        console.log('编码后的封面路径:', encodedPath);
        return `http://localhost:8080/${encodedPath}`;
      }
      return book.cover;
    }
    
    // 如果book.cover不是字符串，使用默认封面
    console.log('封面格式不正确，使用默认封面');
    return defaultCover;
  } catch (error) {
    console.error('获取封面URL时出错:', error);
    return defaultCover;
  }
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.category-header {
  margin-bottom: 2rem;
}

h1 {
  font-size: 1.8rem;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.book-count {
  color: #6b7280;
}

.filters {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
  margin-bottom: 2rem;
  padding: 1rem;
  background-color: #f3f4f6;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.filter-group label {
  color: #4b5563;
  font-weight: 500;
}

.filter-group select {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background-color: white;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 2rem;
}

.book-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;
}

.book-card:hover {
  transform: translateY(-5px);
}

.book-cover {
  height: 250px;
  overflow: hidden;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-info {
  padding: 1rem;
}

.book-info h4 {
  margin: 0 0 0.5rem;
  font-size: 1.1rem;
  color: #1f2937;
}

.book-author {
  color: #6b7280;
  margin: 0.25rem 0;
  font-size: 0.9rem;
}

.book-price {
  font-weight: bold;
  color: #ef4444;
  margin: 0.5rem 0;
}

.book-seller {
  color: #6b7280;
  font-size: 0.9rem;
  margin: 0.25rem 0;
}

.book-tags {
  display: flex;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.tag {
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
}

.tag-new {
  background-color: #dcfce7;
  color: #166534;
}

.tag-good {
  background-color: #fef3c7;
  color: #92400e;
}

.tag-used {
  background-color: #fee2e2;
  color: #991b1b;
}

.no-results {
  text-align: center;
  padding: 3rem 0;
}

.no-results p {
  font-size: 1.2rem;
  color: #4b5563;
  margin-bottom: 1.5rem;
}

.back-link {
  display: inline-block;
  padding: 0.75rem 1.5rem;
  background-color: #3b82f6;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  font-weight: 500;
}

.back-link:hover {
  background-color: #2563eb;
}
</style> 